(function($) {
	$(':text[rel~=team-username]').live("blur", function(e) {
		e.preventDefault();
		var field = $(this);
		var form_container = field.parents('form');
		var team_container = field.parents('div.field.teammember');
		if(field.val() == ''){
			team_container.find('input[rel~=team-id]').val('');
		    team_container.find('input[rel~=team-name]').val('');
		    team_container.find('input[rel~=team-rank]').val('');
			return false;
		}
		
		form_container.find('input[type="submit"], input[type="button"], button').prop('disabled', true);
		field.prop('disabled', true);
		$.getJSON($(this).data('url'), {'username': field.val(), 'ownself': field.data('ownself'), 'upline': field.data('upline')})
		.always(function() {
			form_container.find('input[type="submit"], input[type="button"], button').prop('disabled', false);
			field.prop('disabled', false);
  		})
		.done(function(data) {
		    if(data.result == 'success'){
		    	team_container.find('input[rel~=team-id]').val(data.id);
		    	team_container.find('input[rel~=team-name]').val(data.name);
		    	team_container.find('input[rel~=team-rank]').val(data.rank);
		    } else {
		    	alert(data.msg);
		    	team_container.find('input[rel~=team-id]').val('');
		    	team_container.find('input[rel~=team-name]').val('');
		    	team_container.find('input[rel~=team-rank]').val('');
			    field.val('').focus();
		    }
		})
		.fail(function( jqxhr, textStatus, error ) {
			alert(ss.i18n._t('TeamMemberField.ERROR_LOADING', 'Error occur while loading, please try again.'));
		    team_container.find('input[rel~=team-id]').val('');
	    	team_container.find('input[rel~=team-name]').val('');
	    	team_container.find('input[rel~=team-rank]').val('');
		    field.val('').focus();
		});
	});
})(jQuery);
